{% extends 'preheat/base.html' %}

{% block title %}{{ task.name }} - 自动任务详情 - CDN预热平台{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">
            <h3>自动任务详情</h3>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <h4>{{ task.name }}</h4>
                    <p class="text-muted mb-1">创建时间：{{ task.created_time|date:"Y-m-d H:i:s" }}</p>
                    <p class="text-muted mb-1">更新时间：{{ task.updated_time|date:"Y-m-d H:i:s" }}</p>
                </div>
                <div class="col-md-6 text-right">
                    {% if task.is_active %}
                        <span class="badge badge-success">已启用</span>
                    {% else %}
                        <span class="badge badge-secondary">已禁用</span>
                    {% endif %}
                </div>
            </div>
            
            <div class="mt-4">
                <div class="row">
                    <div class="col-md-4">
                        <strong>任务类型：</strong>
                        <span>{{ task.get_task_type_display }}</span>
                    </div>
                    <div class="col-md-4">
                        <strong>执行间隔：</strong>
                        <span>{{ task.interval }} {{ task.get_task_type_display }}</span>
                    </div>
                    <div class="col-md-4">
                        <strong>上次执行：</strong>
                        <span>
                            {% if task.last_executed_time %}
                                {{ task.last_executed_time|date:"Y-m-d H:i:s" }}
                            {% else %}
                                从未执行
                            {% endif %}
                        </span>
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <strong>请求地址列表：</strong>
                <ul class="list-unstyled pl-0 mt-2">
                    {% for url in task.request_urls.all %}
                        <li>{{ url.url }} - {{ url.cdn_domain.domain }}</li>
                    {% empty %}
                        <li class="text-muted">暂无请求地址</li>
                    {% endfor %}
                </ul>
            </div>
            
            <div class="mt-4">
                <strong>执行服务器：</strong>
                <ul class="list-unstyled pl-0 mt-2">
                    {% for server in task.servers.all %}
                        <li>{{ server.ip }}:{{ server.ssh_port }} {% if server.remark %} - {{ server.remark }}{% endif %}</li>
                    {% empty %}
                        <li class="text-muted">暂无执行服务器</li>
                    {% endfor %}
                </ul>
            </div>
            
            {% if task.description %}
            <div class="mt-4">
                <strong>任务描述：</strong>
                <p class="mt-2 pl-3 border-l-2 border-primary">{{ task.description }}</p>
            </div>
            {% endif %}
            
            <div class="mt-4 d-flex justify-content-start">
                <a href="{% url 'preheat:auto_task_list' %}" class="btn btn-secondary">返回列表</a>
            </div>
        </div>
    </div>
    
    <!-- 执行结果历史 -->
    <div class="card">
        <div class="card-header bg-info text-white">
            <h3>执行结果历史</h3>
        </div>
        <div class="card-body">
            {% if execution_results %}
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>执行时间</th>
                        <th>状态</th>
                        <th>耗时</th>
                        <th>成功数量</th>
                        <th>失败数量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for result in execution_results %}
                    <tr>
                        <td>{{ result.execution_time|date:"Y-m-d H:i:s" }}</td>
                        <td>
                            {% if result.success and result.failed_count == 0 %}
                                <span class="badge badge-success">成功</span>
                            {% elif result.success and result.failed_count > 0 %}
                                <span class="badge badge-warning">部分成功</span>
                            {% else %}
                                <span class="badge badge-danger">失败</span>
                            {% endif %}
                        </td>
                        <td>-</td>
                        <td>{{ result.success_count|default:"0" }}</td>
                        <td>{{ result.failed_count|default:"0" }}</td>
                        <td>
                            <button class="btn btn-info btn-sm" data-toggle="modal" data-target="#resultDetailModal" data-result-id="{{ result.id }}">
                                详情
                            </button>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            {% else %}
            <p class="text-center text-muted">暂无执行结果记录</p>
            {% endif %}
        </div>
    </div>
</div>

<!-- 自定义执行结果详情模态框 -->
<div id="resultDetailModal" class="modal-backdrop" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">执行结果详情</h5>
                <button type="button" id="closeModalBtn" class="close-modal-btn">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div id="resultDetailContent" class="modal-body">
                <!-- 结果详情将通过JavaScript动态加载 -->
                <p class="text-center">加载中...</p>
            </div>
            <div class="modal-footer">
                <button type="button" id="closeModalButton" class="btn btn-secondary">关闭</button>
            </div>
        </div>
    </div>
</div>

<style>
    .card {
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .card-header {
        border-radius: 8px 8px 0 0;
    }
    
    .table {
        margin-bottom: 0;
    }
    
    .badge {
        font-size: 0.8rem;
        padding: 0.4em 0.8em;
    }
    
    .border-l-2 {
        border-left-width: 2px !important;
    }
    
    /* 自定义模态框样式 */
    .modal-backdrop {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1050; /* 确保模态框在最上层 */
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .modal-dialog {
        width: 100%;
        max-width: 500px;
        margin: 1.75rem;
        z-index: 1060;
    }
    
    .modal-content {
        position: relative;
        background-color: #ffffff;
        background-clip: padding-box;
        border: 1px solid rgba(0, 0, 0, 0.2);
        border-radius: 0.3rem;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
        outline: 0;
    }
    
    .modal-header {
        padding: 1rem;
        border-bottom: 1px solid #dee2e6;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .modal-title {
        margin: 0;
        font-size: 1.125rem;
        font-weight: 600;
        line-height: 1.5;
    }
    
    .close-modal-btn {
        float: right;
        font-size: 1.5rem;
        font-weight: 700;
        line-height: 1;
        color: #000;
        text-shadow: 0 1px 0 #fff;
        opacity: 0.5;
        background: transparent;
        border: 0;
        padding: 0;
        cursor: pointer;
        -webkit-appearance: button;
    }
    
    .close-modal-btn:hover {
        color: #000;
        text-decoration: none;
        opacity: 0.75;
    }
    
    .modal-body {
        position: relative;
        padding: 1rem;
        max-height: 400px;
        overflow-y: auto;
    }
    
    .modal-footer {
        padding: 1rem;
        border-top: 1px solid #dee2e6;
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }
    
    .text-center {
        text-align: center;
    }
</style>

<script>
    // 执行结果详情模态框处理
    $(document).ready(function() {
        // 获取模态框元素
        var modal = $('#resultDetailModal');
        var contentDiv = $('#resultDetailContent');
        var closeModalBtn = $('#closeModalBtn');
        var closeModalButton = $('#closeModalButton');
        var isLoading = false;
        
        // 绑定详情按钮点击事件
        $('.btn-info.btn-sm[data-target="#resultDetailModal"]').on('click', function(e) {
            // 阻止事件冒泡
            e.preventDefault();
            e.stopPropagation();
            
            // 防止重复加载
            if (isLoading) return;
            
            try {
                isLoading = true;
                
                var button = $(this);
                var resultId = button.data('result-id');
                
                // 显示加载中状态
                contentDiv.html(
                    '<div class="text-center py-4">' +
                    '<div class="spinner-border" role="status">' +
                    '<span class="sr-only">加载中...</span>' +
                    '</div>' +
                    '<p class="mt-2">正在加载执行结果详情...</p>' +
                    '</div>'
                );
                
                // 显示模态框
                modal.css('display', 'flex');
                
                // 发送AJAX请求获取结果详情
                $.ajax({
                    url: '/get_result_detail/' + resultId + '/',
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        try {
                            // 构建详情内容
                            var statusBadge = data.success ? 
                                '<span class="badge badge-success">成功</span>' : 
                                '<span class="badge badge-danger">失败</span>';
                            
                            var content = 
                                '<div class="mb-3"><strong>执行时间：</strong> <span>' + data.execution_time + '</span></div>' +
                                '<div class="mb-3"><strong>状态：</strong> ' + statusBadge + '</div>' +
                                '<div class="mb-3"><strong>成功URL数量：</strong> <span>' + data.success_count + '</span></div>' +
                                '<div class="mb-3"><strong>失败URL数量：</strong> <span>' + data.failed_count + '</span></div>';
                            
                            // 如果有失败的URL，显示它们
                            if (data.failed_urls) {
                                content += '<div class="mb-3"><strong>失败的URL：</strong></div>';
                                // 将失败的URL转换为列表形式，提高可读性
                                var failedUrls = data.failed_urls.split('\n');
                                // 过滤掉空字符串
                                var nonEmptyUrls = failedUrls.filter(function(url) { return url.trim() !== ''; });
                                
                                if (nonEmptyUrls.length > 0) {
                                    content += '<div class="bg-danger bg-opacity-10 border border-danger rounded p-3 mb-3">';
                                    content += '<ul class="list-unstyled mb-0">';
                                    nonEmptyUrls.forEach(function(url, index) {
                                        // 除了最后一个元素外，其他都添加底边框
                                        var borderClass = index < nonEmptyUrls.length - 1 ? 'border-b border-danger border-opacity-20' : '';
                                        content += '<li class="py-1 ' + borderClass + '">' + url + '</li>';
                                    });
                                    content += '</ul>';
                                    content += '</div>';
                                }
                            }
                            
                            contentDiv.html(content);
                        } catch (error) {
                            console.error('处理结果数据时出错:', error);
                            contentDiv.html(
                                '<div class="alert alert-danger" role="alert">' +
                                '处理执行结果数据失败，请稍后再试' +
                                '</div>'
                            );
                        } finally {
                            isLoading = false;
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('获取执行结果详情失败:', error);
                        contentDiv.html(
                            '<div class="alert alert-danger" role="alert">' +
                            '加载执行结果详情失败，请稍后再试' +
                            '</div>'
                        );
                        isLoading = false;
                    }
                });
            } catch (error) {
                console.error('显示模态框时出错:', error);
                isLoading = false;
            }
        });
        
        // 关闭模态框函数
        function closeModal() {
            modal.css('display', 'none');
            contentDiv.html('<p class="text-center">加载中...</p>');
        }
        
        // 绑定关闭按钮事件
        closeModalBtn.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeModal();
        });
        
        closeModalButton.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeModal();
        });
        
        // 点击模态框外部关闭
        modal.on('click', function(event) {
            if (event.target === modal[0]) {
                closeModal();
            }
        });
        
        // 点击模态框内容区域不关闭
        modal.find('.modal-dialog').on('click', function(e) {
            e.stopPropagation();
        });
        
        // ESC键关闭模态框
        $(document).on('keydown', function(event) {
            if (event.key === 'Escape' && modal.css('display') !== 'none') {
                closeModal();
            }
        });
    });
</script>
{% endblock %}